package com.suep.file.controller;


import com.suep.file.service.IFileService;
import com.suep.system.config.BaseR;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.suep.file.util.FileUtil;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private IFileService fileService;
    /*
    * 文件上传接口
    * */
    @PostMapping("/upload")
    public BaseR<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Integer userId = new Integer(request.getAttribute("userId").toString()); // 获取当前登录用户id
        request.getAttribute("userId"); // 获取当前登录用户id
        try {
            //实际存储文件函数
            String fileName = fileService.saveFile(file, userId);
            return new BaseR<>().ok("文件上传成功: " + fileName);
        } catch (IOException e) {
            return new BaseR<>().error("文件上传失败: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new BaseR<>().error("文件名非法: " + e.getMessage());
        }
    }
    @GetMapping("/download/{fileName}")
    public BaseR<Resource> downloadFile(@PathVariable String fileName , HttpServletResponse response) {
        try {
            Resource resource = fileService.downloadFile(fileName);

            // 直接设置响应头
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + resource.getFilename() + "\"");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

            // 将文件流写入响应体
            try (InputStream inputStream = resource.getInputStream();
                 OutputStream outputStream = response.getOutputStream()) {
                IOUtils.copy(inputStream, outputStream);
                outputStream.flush();
            }
            return new BaseR<>().ok("文件下载成功",resource); // 返回结果对象
        } catch (SecurityException e) {
            return new BaseR<>().error("文件无下载权限: " + e.getMessage());
        } catch (Exception e) {
            return new BaseR<>().error("文件不存在或者已经失效 " + e.getMessage());
        }
    }

    /*
    * 正则表达式捕获路径
    * */

    @GetMapping("/load/**")
    public ResponseEntity<Resource> loadFile(HttpServletRequest request, HttpServletResponse response) {
        String filePath = request.getServletPath();
        filePath = filePath.replace("file/load/", "");
        System.out.println("filePath------------------------"+filePath);
        String fileName = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);

        System.out.println("fileName------------------------"+fileName);

        try {
            // 2. 调用服务层加载文件（需同步修改服务层方法）
            Resource resource = fileService.loadFile(filePath);
            String contentType = FileUtil.determineContentType(fileName);

            // 4. 构建响应实体
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"")
                    .body(resource);
        } catch (SecurityException e) {
            // 403 Forbidden
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .header("Close", "文件无加载权限: " + e.getMessage())
                    .build();
        } catch (Exception e) {
            // 500 Internal Server Error
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .header("Close" , "文件加载失败: " + e.getMessage())
                    .build();
        }
    }
}
